package com.qingcloud.df.executor.process.common;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.qingcloud.base.exception.WamingException;
import com.qingcloud.df.executor.pojo.process.config.AllowedHosts;
import com.qingcloud.df.executor.pojo.process.config.ResourceRequirements;
import com.qingcloud.df.executor.process.ProcessFactory;
import com.qingcloud.df.executor.utils.ComponentUtil;
import com.qingcloud.df.sdk.component.context.CompInstContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;

public class DaemonProcessFactory  implements ProcessFactory {
    private static final Logger logger = LoggerFactory.getLogger(DaemonProcessFactory.class);
    @Override
    public Process bulidProcess(String imageName,
                                String suffix,
                                String rootPath,
                                String componentNameEn,
                                Map<String, String> files,
                                String entrypoint,
                                ResourceRequirements resourceRequirements,
                                AllowedHosts allowedHosts,
                                String... jarCommand) {

        try {
            logger.info("开始启动[{}]组件的独立执行文件", suffix);
            //创建java启动命令
            final List<String> cmd = Lists.newArrayList(jarCommand);
            logger.info("Preparing command: {}", Joiner.on(" ").join(cmd));
            ProcessBuilder processBuilder = new ProcessBuilder(cmd);
            Path workspaceRoot = Files.createTempDirectory(rootPath);
            processBuilder.directory(workspaceRoot.toFile());
            return processBuilder.start();

        } catch (final IOException e) {
            throw new WamingException(9000,e.getMessage());
        }
    }

    @Override
    public void processStop(String imageName, String suffix) {

    }
}
